<template>
  <van-uploader
    :after-read="afterRead"
    v-model="fileList"
    :max-count="maxCount"
    :disabled="disabled"
    :accept="accept"
  ></van-uploader>
</template>

<script>
import Vue from "vue";
import TypeHelper from "@/utils/helper/TypeHelper";
import { ACCESS_TOKEN } from "@/store/mutation-types";
const uuid = require("uuid");

export default {
  props: {
    // eslint-disable-next-line vue/require-prop-type-constructor
    value: "", // 字符串或字符串数组
    maxCount: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      defaule: "image/*"
    }
  },
  mounted() {
    if (this.maxCount === 1) {
      this.value = this.value || "";
    } else {
      this.value = this.value || [];
    }
    this.checkType(this.value);

    this.refresh();
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    value(val) {
      this.checkType(val);

      this.value = val;
      this.refresh();
    }
  },
  methods: {
    checkType(val) {
      if (this.maxCount === 1 && TypeHelper.isArray(val)) {
        throw "maxCount=1时model不能为Array";
      }
      if (this.maxCount > 1 && !TypeHelper.isArray(val)) {
        throw "maxCount>1时model必须为Array<String>";
      }
    },
    refresh() {
      if (this.maxCount < 1) {
        throw "maxCount必须>=1";
      }
      if (this.value) {
        let urls = [];

        if (TypeHelper.isString(this.value)) {
          urls.push(this.value);
        } else if (TypeHelper.isArray(this.value)) {
          urls.push(...this.value);
        } else {
          throw "value必须为字符串或数组";
        }

        this.fileList = urls.map(x => {
          return {
            name: this.getFileName(x),
            uid: uuid.v4(),
            status: "done",
            url: x
          };
        });
      } else {
        this.fileList = [];
      }
    },
    getFileName(url) {
      let reg = /^.*\/(.*?)$/;
      let match = reg.test(url);
      if (match) {
        return RegExp.$1;
      } else {
        return "";
      }
    },
    //  替换默认上传:action="`${$rootUrl}/Base_Manage/Upload/UploadFileByForm`"
    afterRead(options) {
      var file = options.file;
      var param = new FormData(); // 创建form对象
      param.append("file", file); // 通过append向form对象添加数据

      var config = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      if (Vue.ls.get(ACCESS_TOKEN)) {
        config.headers.Authorization = "Bearer " + Vue.ls.get(ACCESS_TOKEN);
      }
      var url = `${this.$rootUrl}/Base_Manage/Upload/UploadFileByForm`;
      this.$http.post(url, param, config).then(res => {
        var file = {
          name: this.getFileName(res.url),
          uid: uuid.v4(),
          status: "done",
          url: res.url
        };
        this.fileList.push(file);
        var urls = this.fileList
          .filter(x => x.status === "done")
          .map(x => x.url || x.response.url);
        var newValue = this.maxCount === 1 ? urls[0] : urls;
        // 双向绑定
        this.$emit("input", newValue);
      });
    }
  }
};
</script>
